package cn.onein.edu.backend.jms.consumer;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.log4j.Logger;

import cn.onein.edu.backend.job.JobType;
import cn.onein.edu.backend.service.DailyUserActionsService;
import cn.onein.edu.backend.util.EmailUtil;
import cn.onein.edu.backend.vo.DailyAcitonMailVO;
import cn.onein.edu.common.MailType;
import cn.onein.edu.common.base.JmsSupport;
import cn.onein.edu.util.DateUtil;

/**
 * 处理分发、发送邮件的JMS消息消费者，支持并发处理，并发数参见：app-mq.xml
 * 
 * @author Upton
 * 
 */
public class SendMailConsumer implements MessageListener {

	Logger logger = Logger.getLogger(SendMailConsumer.class);
	
	private DailyUserActionsService dailyUserActionsService;
	
	public void setDailyUserActionsService(DailyUserActionsService dailyUserActionsService){
		this.dailyUserActionsService = dailyUserActionsService;
	}

	@Override
	public void onMessage(Message message) {
		try {
			String mailTypeStr = message.getStringProperty(JmsSupport.MSG_KEY_SEND_MAIL_TYPE);

			MailType mailType = MailType.valueOf(mailTypeStr);

			switch (mailType) {
				case Register:
					sendRegisterMail(mailType, message);
					break;
				case PasswordRetrieve:
					sendPasswordRetrieveMail(mailType, message);
					break;
				case ShareAction:
					sendShareActionMail(mailType, message);
					break;
				case ChangeEmail:
					sendChangeEmailMail(mailType, message);
					break;
				case DailyAction:
					sendDailyActionMail(mailType, message);
					break;
				case WeeklyReport:
					sendWeeklyReportMail(mailType, message);
					break;
				case JobStart:
				case JobEnd:
				case JobError:
					sendJobMail(mailType, message);
					break;
				case FeedBack:
					sendFeedBack(mailType, message);
					break;
				default:
					logger.error("发送邮件类型错误！！！");
					break;
			}
		} catch (JMSException e) {
			logger.error("取得MQ消息时发生错误！", e);
		} catch (EmailException e) {
			logger.error("发送邮件时发生错误！", e);
		}
	}

	/**
	 * 用户注册时发送邮件
	 * @param mailType
	 * @param message
	 * @throws JMSException
	 * @throws EmailException
	 */
	private void sendRegisterMail(MailType mailType, Message message)
			throws JMSException, EmailException {
		String userMail = message.getStringProperty(JmsSupport.MSG_KEY_USER_EMAIL);

		HtmlEmail email = EmailUtil.getHtmlEmail();
		String template = EmailUtil.getEmailTemplate(mailType, new Object[]{userMail});

		email.setSubject("注册成功 | 万应儿童教育");
		email.setHtmlMsg(template);

		email.addTo(userMail);
		email.send();
	}

	/**
	 * 发送找回密码邮件
	 * @param mailType
	 * @param message
	 * @throws JMSException 
	 * @throws EmailException 
	 */
	private void sendPasswordRetrieveMail(MailType mailType, Message message) throws JMSException, EmailException {
		String userMail = message.getStringProperty(JmsSupport.MSG_KEY_USER_EMAIL);
		String newPassword = message.getStringProperty(JmsSupport.MSG_KEY_USER_NEW_PASS); 
		

		HtmlEmail email = EmailUtil.getHtmlEmail();
		String template = EmailUtil.getEmailTemplate(mailType, new Object[]{userMail, newPassword});

		email.setSubject("密码找回 | 万应儿童教育");
		email.setHtmlMsg(template);

		email.addTo(userMail);
		email.send();
	}

	/**
	 * 发送分享行动指南邮件
	 * @param mailType
	 * @param message
	 * @throws JMSException 
	 * @throws EmailException 
	 */
	private void sendShareActionMail(MailType mailType, Message message) throws JMSException, EmailException {
		String userMail = message.getStringProperty(JmsSupport.MSG_KEY_USER_EMAIL);
		String sharedActionUrl = message.getStringProperty(JmsSupport.MSG_KEY_SHARED_URL); 
		

		HtmlEmail email = EmailUtil.getHtmlEmail();
		String msg = EmailUtil.getEmailTemplate(mailType, new Object[]{userMail, sharedActionUrl});

		email.setSubject("您的朋友和你分享 | 万应儿童教育");
		email.setHtmlMsg(msg);

		email.addTo(userMail);
		email.send();
	}
	
	/**
	 * 发送修改eMail邮件
	 * @param mailType
	 * @param message
	 * @throws JMSException 
	 * @throws EmailException 
	 */
	private void sendChangeEmailMail(MailType mailType, Message message) throws JMSException, EmailException {
		String userMail = message.getStringProperty(JmsSupport.MSG_KEY_USER_EMAIL);
		String changeEmailUrl = message.getStringProperty(JmsSupport.MSG_KEY_CHANGE_EMAIL_URL); 
		

		HtmlEmail email = EmailUtil.getHtmlEmail();
		String msg = EmailUtil.getEmailTemplate(mailType, new Object[]{userMail, changeEmailUrl});

		email.setSubject("修改邮箱确认 | 万应儿童教育");
		email.setHtmlMsg(msg);

		email.addTo(userMail);
		email.send();
	}

	/**
	 * 发送每日行动指南邮件
	 * @param mailType
	 * @param message
	 * @throws JMSException
	 * @throws EmailException 
	 */
	private void sendDailyActionMail(MailType mailType, Message message) throws JMSException, EmailException {
		// 用户ID
		Long userid = Long.valueOf(message.getStringProperty(JmsSupport.MSG_KEY_USER_ID));
		// 用户Email
		String emailAddress = message.getStringProperty(JmsSupport.MSG_KEY_USER_EMAIL);
		// 用户名
		String userName = message.getStringProperty(JmsSupport.MSG_KEY_USER_NAME);
		// 用户昵称
		String nickName = message.getStringProperty(JmsSupport.MSG_KEY_USER_NICK_NAME);
		
		Date today = new Date();
		// 取得详细的每日行动指南信息
		DailyAcitonMailVO dailyAcitonMailVO = dailyUserActionsService.getDailyActionByUserIDAndDate(userid, today);
		
		// 查询到了今天的每日行动指南
		if(dailyAcitonMailVO != null){
			String userTitle = emailAddress;
			if(userName != null && userName.trim().length() > 0){
				userTitle = userName;
			}
			
			if(nickName != null && nickName.trim().length() >0){
				userTitle = nickName;
			}
			
			// 设置用户显示时间
			String dateStr = DateUtil.mailDispDateStr(today);
			
			// 每日行动指南的详细内容
			String fullText;
			if(dailyAcitonMailVO.getActive()){
				// 当前会员服务有效
				fullText = dailyAcitonMailVO.getFullText();
			}
			else{
				// 当前会员服务失效时，替换为推广内容
				fullText = EmailUtil.getEmailTemplate(MailType.AdTemplate); 
			}
			
			Object[] args = new Object[]{
										dateStr,
										userTitle,
										dailyAcitonMailVO.getIntroText(),
										fullText,
										dailyAcitonMailVO.getDailyNote()};
			
			String htmlMsg = EmailUtil.getEmailTemplate(mailType, args);
			
			HtmlEmail email = EmailUtil.getHtmlEmail();
			
			// 邮件的主题
			String subject = "每日行动指南 | 万应儿童教育";
			email.setSubject(subject);			
			email.setHtmlMsg(htmlMsg);	
			email.addTo(emailAddress);
			
			email.send();
		}
		else{ // 没查询到每日行动指南
			logger.error("用户ID[" + userid + "]没查询到每日行动指南,请检查！");
		}
	}

	/**
	 * 发送用户周报邮件
	 * @param mailType
	 * @param message
	 */
	private void sendWeeklyReportMail(MailType mailType, Message message) {

	}

	/**
	 * 发送监控邮件
	 * @param mailType
	 * @param message
	 * @throws JMSException
	 * @throws EmailException
	 */
	private void sendJobMail(MailType mailType, Message message) throws JMSException, EmailException {
		String userMail = message.getStringProperty(JmsSupport.MSG_KEY_USER_EMAIL);
		String jobTypeStr = message.getStringProperty(JmsSupport.MSG_KEY_JOB_TYPE);
		String jobMessage = message.getStringProperty(JmsSupport.MSG_KEY_JOB_MESSAGE);
		
		JobType jobType = JobType.valueOf(jobTypeStr);
				
		HtmlEmail email = EmailUtil.getHtmlEmail();
		String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		String subject = "JOB监控邮件 | " + date + "-" + jobType.toString() + "." + mailType.toString();
		
		email.setSubject(subject);
				
		String htmlMsg = EmailUtil.getEmailTemplate(mailType, new Object[]{subject, jobMessage});
		
		email.setHtmlMsg(htmlMsg);

		email.addTo(userMail);
		email.send();
	}
	
	/**
	 * 发送意见反馈邮件
	 * @param mailType
	 * @param message
	 * @throws JMSException
	 * @throws EmailException
	 */
	private void sendFeedBack(MailType mailType, Message message) throws JMSException, EmailException {		
        String toMail = EmailUtil.SERVICE_EMAIL;
		
		String title = message.getStringProperty(JmsSupport.MSG_KEY_FEEDBACK_TITLE);
		String mobile = message.getStringProperty(JmsSupport.MSG_KEY_FEEDBACK_MOBILE);
		String userEmail = message.getStringProperty(JmsSupport.MSG_KEY_FEEDBACK_EMAIL);
		String content = message.getStringProperty(JmsSupport.MSG_KEY_FEEDBACK_CONTENT);
				
		HtmlEmail email = EmailUtil.getHtmlEmail();
		String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		String subject = "意见反馈，请及时处理";
		
		email.setSubject(subject);
				
		String htmlMsg = EmailUtil.getEmailTemplate(mailType, 
				new Object[]{date, title, mobile, userEmail, content});
		
		email.setHtmlMsg(htmlMsg);

		email.addTo(toMail);
		email.send();
	}
}